<template>
  <div class="echarts" ref="chartRef"></div>
</template>

<script setup>
import { getVideoViews } from "@/api/IssueData";
import * as echarts from "echarts";
import { onMounted, onUnmounted, ref, nextTick } from "vue";

const data = ref(null);
const chartRef = ref(null);
let myChart = null;

// 记录当前显示的最后一个元素在data中的索引
let currentIndex = 4;

// 得到data里的前5个数据
const rdata = {
  cate: [],
  value: []
}

// 获取前5个数据
const getRdata = () => {
  if (data.value && data.value.cate) {
    rdata.cate = data.value.cate.slice(0, 5);
    rdata.value = data.value.value.slice(0, 5);
  }
}

const initChart = () => {
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "line"
      }
    },
    grid: {
      top: 10,
      bottom: 30,
      left: 50,
      right: 20
    },
    xAxis: {
      data: rdata.cate,
      axisTick: {
        alignWithLabel: true
      },
      boundaryGap: false,
    },
    yAxis: {
      show: true,
      type: "value",
      name: "数量",
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
          color: '#ccc',
          opacity: 0.5
        }
      }
    },
    series: [
      {
        data: rdata.value,
        type: "line",
        smooth: true,
        showSymbol: true,
        symbolSize: 8,
        itemStyle: {
          color: '#fc903a'
        },
        lineStyle: {
          color: '#fc903a'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0.3,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: '#fc903a' // 0% 处的颜色
            }, {
              offset: 1, color: '#000' // 100% 处的颜色
            }],
            global: false // 缺省为 false
          }
        },
      }
    ],
  };

  myChart = echarts.init(chartRef.value);
  myChart.setOption(option);
};

onMounted(async () => {
  const result = await getVideoViews();
  data.value = result.data;
  getRdata();
  initChart();

  setInterval(() => {
    updateData();
  }, 4000);
});

function updateData() {
  if (!data.value || !data.value.cate) return;

  // 移除第一项
  rdata.cate.shift();
  rdata.value.shift();

  // 更新currentIndex，如果到达data的末尾则重置为0
  currentIndex = (currentIndex + 1) % data.value.cate.length;

  // 添加data中的下一项到末尾
  rdata.cate.push(data.value.cate[currentIndex]);
  rdata.value.push(data.value.value[currentIndex]);

  // 更新图表
  myChart.setOption({
    xAxis: {
      data: rdata.cate
    },
    series: [
      {
        data: rdata.value
      }
    ]
  })
}

onUnmounted(() => {
  if (myChart) {
    myChart.dispose();
  }
});
</script>

<style scoped>
.echarts {
  width: 100%;
  height: 90%;
}
</style>
